/**
 * @Description 
 * @Version 
 * @Author Dong
 * @Date 2021-03-08 15:27:46
 * @LastEditors Dong
 * @LastEditTime 2021-03-09 09:24:06
 * @FilePath \fed-e-task-04-06\code\work\src\app\store\reducers\todo.reducer.ts
 */
// src\app\store\reducers\todo.reducer.ts
import { createReducer, on } from '@ngrx/store';
import { addTodo, changeTodo, deleteTodo, initTodos } from '../actions/todo.actions';
import { v4 as uuidv4 } from 'uuid'
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';

export const todoFeatureKey = 'todo';

// todo 列表数据接口
export interface Todo {
  id: string
  value: string
  checked: boolean
}

// 继承 EntityState 数据类型
export interface State extends EntityState<Todo> {}

// 创建实体适配器对象
export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>()

// 获取初始状态
export const initialState: State = adapter.getInitialState()

// 创建 reducer
export const reducer = createReducer(
  initialState,
  // 为 todo 列表添加一条数据 id 随机
  on(addTodo, (state, action) => adapter.addOne({
    id: uuidv4(),
    value: action.value,
    checked: false
  }, state)),
  // 根据 id 删除 todo 列表中单条数据
  on(deleteTodo, (state, action) => adapter.removeOne(action.id, state)),
  // 修改单条 todo 数据
  on(changeTodo, (state, action) => adapter.setOne({
    id: action.id,
    value: action.value,
    checked: action.checked
  }, state)),
  // 初始化 todo 列表
  on(initTodos, (state, action) => adapter.addMany(action.todos, state))
);

